package czh.cocoa.foundation;

import java.util.Calendar;
import java.util.Date;

public class NSCalendar extends NSObject {
	
	public final static int NSYearCalendarUnit = 1 << 2;
	public final static int NSMonthCalendarUnit = 1 << 3;
	public final static int NSDayCalendarUnit = 1 << 4;
	public final static int NSHourCalendarUnit = 1 << 5;
	public final static int NSMinuteCalendarUnit = 1 << 6;
	public final static int NSSecondCalendarUnit = 1 << 7;
	public final static int NSWeekdayCalendarUnit = 1 << 9;
	
	private Calendar mCalendar;
	
	public static NSCalendar currentCalendar() {
		return new NSCalendar();
	}
	
	private NSCalendar() {
		mCalendar = Calendar.getInstance(); 
	}
	
	public NSDateComponents componentsFromDate(int unitFlags, NSDate date) {
		mCalendar.setTime(date.date()); 
		
		NSDateComponents components = new NSDateComponents();
		
		if ((unitFlags & NSYearCalendarUnit) == NSYearCalendarUnit) { 
			int year = mCalendar.get(Calendar.YEAR);
			components.setYear(year);
		}
		if ((unitFlags & NSMonthCalendarUnit) == NSMonthCalendarUnit) { 
			int month = mCalendar.get(Calendar.MONTH);
			components.setMonth(month);
		}
		if ((unitFlags & NSDayCalendarUnit) == NSDayCalendarUnit) { 
			int day = mCalendar.get(Calendar.DAY_OF_MONTH);
			components.setDay(day);
		}
		if ((unitFlags & NSHourCalendarUnit) == NSHourCalendarUnit) { 
			int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
			components.setHour(hour);
		}
		if ((unitFlags & NSMinuteCalendarUnit) == NSMinuteCalendarUnit) { 
			int minute = mCalendar.get(Calendar.MINUTE);
			components.setMinute(minute);
		}
		if ((unitFlags & NSSecondCalendarUnit) == NSSecondCalendarUnit) { 
			int second = mCalendar.get(Calendar.SECOND);
			components.setSecond(second);
		}
		if ((unitFlags & NSWeekdayCalendarUnit) == NSWeekdayCalendarUnit) { 
			int weekday = mCalendar.get(Calendar.DAY_OF_WEEK);
			components.setWeekday(weekday);
		}
		
		return components;
	}
	
	public NSDate dateFromComponents(NSDateComponents components) {
		int year = components.year();
		if (year > 0) {
			mCalendar.set(Calendar.YEAR, year); 
		}
		int month = components.month();
		if (month > 0) {
			mCalendar.set(Calendar.MONTH, year); 
		}
		int day = components.day();
		if (day > 0) {
			mCalendar.set(Calendar.DAY_OF_MONTH, year); 
		}
		int hour = components.hour();
		if (hour >= 0) {
			mCalendar.set(Calendar.HOUR_OF_DAY, year); 
		}
		int minute = components.minute();
		if (minute >= 0) {
			mCalendar.set(Calendar.MINUTE, year); 
		}
		int second = components.second();
		if (second >= 0) {
			mCalendar.set(Calendar.SECOND, year); 
		}
		Date date = mCalendar.getTime();
		return new NSDate(date);
	}
	
}
